package com.turing.post.common.impl;

import java.math.BigInteger;
import java.util.Date;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.ejb.TransactionAttribute;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.Global;
import com.turing.post.common.util.PCPSCommonDao;
import com.turing.post.common.util.SysOpUser;
import com.turing.post.common.util.SysOpUserDao;
import com.turing.post.organization.util.IssueCompany;
import com.turing.post.organization.util.IssueCompanyDao;
import com.turing.post.organization.util.SysBranch;
import com.turing.post.organization.util.SysBranchDao;
import com.turing.post.util.PCPSUtil;
import com.turing.post.util.PCPSWebInput;

/**
 * @通用方法类
 * @author zhang xiao pan
 * @创建时间：Dec 15, 2012
 */
@Stateless(mappedName = "common.impl.PCPSCommonDaoImpl")
@Remote
@Local
public class PCPSCommonDaoImpl implements PCPSCommonDao {

	// 用户表
	@EJB(mappedName = "common.impl.SysOpUserDaoImpl")
	private SysOpUserDao sysOpUserDaoImpl;

	@EJB(mappedName = "organization.impl.SysBranchDaoImpl")
	private SysBranchDao sysBranchDaoImpl;

	@EJB(mappedName = "organization.impl.IssueCompanyDaoImpl")
	private IssueCompanyDao issueCompanyDaoImpl;

	@Resource
	private SessionContext ejbContext;

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	public void rollback() {
		ejbContext.setRollbackOnly();
	}

	/**
	 * @return 系统时间，格式化后只为日期
	 */
	public String getSysTimeFormatYMD() {
		String jpql = "select to_char(sysdate,'yyyy-MM-dd') from dual";
		Query query = _em.createNativeQuery(jpql);
		return (String) query.getSingleResult();
	}

	/**
	 * @return 系统日期，不带时分秒，只为日期
	 */
	public Date getSysDateFormatYMD() {
		String jpql = "select to_date(to_char(sysdate,'yyyy-MM-dd'),'yyyy-mm-dd') from dual";
		Query query = _em.createNativeQuery(jpql);
		return (Date) query.getSingleResult();
	}

	/**
	 * @return 系统时间，格式化后带时分秒
	 */
	public String getSysTimeFormatYMDHMS() {
		String jpql = "select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual";
		Query query = _em.createNativeQuery(jpql);
		return (String) query.getSingleResult();
	}

	/**
	 * 取当前数据库时间
	 * 
	 * @return
	 */
	public Date getDatabaseSysTime() {
		String jpql = "select sysdate from dual";
		Query query = _em.createNativeQuery(jpql);
		return (Date) query.getSingleResult();
	}

	/**
	 * 获取唯一的整数类主键
	 * 
	 * @return
	 */
	@TransactionAttribute(javax.ejb.TransactionAttributeType.REQUIRES_NEW)
	public BigInteger getUniqueIntegerKey() {
		String jpql = "SELECT PCPSSEQUENCE.NEXTVAL FROM DUAL";
		Query query = _em.createNativeQuery(jpql);
		return new BigInteger(query.getSingleResult().toString());
	}

	/**
	 * 获取帐户子系统顺序号
	 * 
	 * @return
	 */
	public BigInteger getAccountSubSystemSeqNo() {
		String jpql = "SELECT PCPSACCSYSSEQUENCE.NEXTVAL FROM DUAL";
		Query query = _em.createNativeQuery(jpql);
		return new BigInteger(query.getSingleResult().toString());
	}

	/**
	 * 获取商户交易子系统顺序号
	 * 
	 * @return
	 */
	public BigInteger getMrchTranSeqNo() {
		String jpql = "SELECT PCPSMRCHTRANSEQUENCE.NEXTVAL FROM DUAL";
		Query query = _em.createNativeQuery(jpql);
		return new BigInteger(query.getSingleResult().toString());
	}

	// 根据操作员号获取日志目录
	@Override
	public String getLogPathByOperId(BigInteger operId) {
		String firstPath = "";
		// 根据操作员号判断归属机构
		SysOpUser user = sysOpUserDaoImpl.getSysOpUserByOperId(operId);
		SysBranch sysBranch = sysBranchDaoImpl.getSysBranchByBranchNo(user
				.getOperBranchNo());
		// 机构类型
		if (sysBranch == null) {
			return "";
		}
		String branchType = sysBranch.getBranchType();
		String branchNo = sysBranch.getBranchNo();
		if (branchType.equals(SysBranch.SYSBRANCH_ISSUECOMPANY)) {
			// 发卡商
			firstPath = branchNo + "/" + operId;
		} else if (branchType.equals(SysBranch.SYSBRANCH_ISSUEBRANCH)) {
			// 发卡商机构
			firstPath = branchNo.substring(0, 6) + "/" + "issuebranch/"
					+ branchNo + "/" + operId;
		} else if (branchType.equals(SysBranch.SYSBRANCH_SALECOMPANY)) {
			// 销售商
			firstPath = branchNo.substring(0, 6) + "/" + "sale/" + branchNo
					+ "/" + operId;
		} else if (branchType.equals(SysBranch.SYSBRANCH_SALEBRANCH)) {
			// 销售商
			firstPath = branchNo.substring(0, 6) + "/" + "salebranch/"
					+ branchNo + "/" + operId;
		} else if (branchType.equals(SysBranch.SYSBRANCH_MERCHANT)
				|| branchType.equals(SysBranch.SYSBRANCH_MERCHANTBRANCH)) {
			firstPath = branchNo.substring(0, 6) + "/" + "merchant/" + branchNo
					+ "/" + operId;
		}
		return firstPath;
	}

	@Override
	public Global getGlobalInfo() {
		return _em.find(Global.class, "1");
	}

	@Override
	public String getOrderNumber(Date now, String saleBranchNo) {
		Date date = null;
		if (now == null) {
			IssueCompany ic = issueCompanyDaoImpl
					.getIssueCompanyByIssueCompanyNo(saleBranchNo.substring(0,
							6));
			date = ic.getTranDate();
		} else {
			date = now;
		}
		Integer seqNo = sysBranchDaoImpl
				.updateSysBranchOrderSeqNo(saleBranchNo);
		return saleBranchNo + PCPSUtil.getPackedYMDString(date)
				+ String.format("%05d", seqNo);
	}

	@Override
	public void setSysLogPath(PCPSWebInput input) {
		if (input != null) {
			if (!PCPSUtil.isEmpty(input.getOperBranchNo())) {
				String logPath = getLogPathByOperId(input.getOperId());
				if (!PCPSUtil.isEmpty(logPath)) {
					PCPSUtil.setWebserviceLogEntry(logPath);
				}
			} else {
				PCPSUtil.setWebserviceLogEntry(input.getOperId().toString());
			}
		}
	}

	@Override
	public void setDataTranferLogPath(String path) {
		PCPSUtil.setWebserviceLogEntry(path);
	}
}